package web.admin.shop.product.checkboxtree;


import application.WicketApplication;
import domain.shop.Category;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IDetachable;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;

import java.io.Serializable;
import java.util.logging.Logger;

class CategoryModel implements IDetachable, Serializable {

    private Long id;
    private transient Category data;
    private transient boolean attached;
    @SpringBean
    private transient ShopAdminService shopAdminService;
    private static Logger logger = Logger.getLogger(CategoryModel.class.getName());

    public CategoryModel(Long id) {
        InjectorHolder.getInjector().inject(this);
        this.id = id;
        attached = false;
    }

    public CategoryModel(Category category) {
        InjectorHolder.getInjector().inject(this);
        this.data = category;
        this.id = category.getId();
        attached = true;
    }

    @Override
    public String toString() {
        return getCategory() == null ? "" : getCategory().getName();
    }

    public Category getCategory() {
        load();
        return data;
    }

    public Long getId() {
        return id;
    }

    public void detach() {
        data = null;
        attached = false;
    }

    public void load() {
        if (!attached && id != null) {
            try {
                data = getShopAdminService().findCategoryById(id);
                attached = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //kdyz se loadne v jinym tabu stranka, pak se klikne v editaci produktu na ulozit, tak bude shopAdminService null
    public ShopAdminService getShopAdminService() {
        if (shopAdminService == null) {
            shopAdminService = (ShopAdminService) WicketApplication.getInstance().getBean("shopAdminService");
        }
        return shopAdminService;
    }
}

